package com.hyt.it.ogt.pj.data.service.kw.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.hyt.core.base.BaseServiceImpl;
import com.hyt.it.ogt.pj.data.mapper.kw.ExamCandidateMapper;
import com.hyt.it.ogt.pj.data.mapper.kw.ExamPaperMapper;
import com.hyt.it.ogt.pj.data.mapper.kw.SjItemFileMapper;
import com.hyt.it.ogt.pj.data.mapper.kw.SjPaperMapper;
import com.hyt.it.ogt.pj.data.model.dto.PaperDTO;
import com.hyt.it.ogt.pj.data.model.entity.kw.ExamPaper;
import com.hyt.it.ogt.pj.data.model.entity.kw.ExamPaperPackage;
import com.hyt.it.ogt.pj.data.model.entity.pj.PaperItemFile;
import com.hyt.it.ogt.pj.data.model.vo.kw.ProjectVO;
import com.hyt.it.ogt.pj.data.model.vo.kwgov.NowTestNowDataVO;
import com.hyt.it.ogt.pj.data.model.vo.pj.*;
import com.hyt.it.ogt.pj.data.service.kw.IExamCandidateService;
import com.hyt.it.ogt.pj.data.service.kw.IExamPaperPackageService;
import com.hyt.it.ogt.pj.data.service.kw.IExamPaperService;
import com.hyt.it.ogt.pj.data.service.kwgov.IKwGovTaskService;
import com.hyt.it.ogt.pj.data.utils.DateTimeUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 考试-试卷 服务实现类
 * </p>
 *
 * @author liuqi
 * @date 2022-06-07
 */
@Service
@Slf4j
public class ExamPaperServiceImpl extends BaseServiceImpl<ExamPaperMapper, ExamPaper> implements IExamPaperService {

	@Resource
	private SjPaperMapper sjPaperMapper;

	@Resource
	private ExamPaperMapper examPaperMapper;

	@Resource
	private IExamCandidateService iExamCandidateService;

	@Resource
	private IExamPaperPackageService iExamPaperPackageService;

	@Resource
	private ExamCandidateMapper examCandidateMapper;

	@Resource
	private IKwGovTaskService kwgovTaskService;

	@Resource
	private SjItemFileMapper sjItemFileMapper;

	@DS("kw_read")
	@Override
	public List<PaperDataVO> getPaperBySubjectId(String subjectId, String projectId, String admissionNumber) {
		// 获取科目id对应的试卷id、试卷版本号
		List<PaperDTO> paperDTOList = iExamCandidateService.getPaperDTO(subjectId, projectId, admissionNumber);
		if(CollectionUtil.isNotEmpty(paperDTOList)) {
		    log.info("# getPaperBySubjectId {},{},{}, size: {}" , subjectId, projectId, admissionNumber, paperDTOList.size());
		}else {
		    log.info("# getPaperBySubjectId {},{},{}, size is null" , subjectId, projectId, admissionNumber);
		}
		// 创建试卷包/试卷List
		List<PackageDataVO> packageDataVOList = new ArrayList<>();
		// 根据试卷id、试卷版本号获取试卷或试卷包数据
		for (PaperDTO paperDTO : paperDTOList) {
			// 创建试卷包/试卷数据
			PackageDataVO packageDataVO = new PackageDataVO();
			// 创建试卷数据
			List<PaperDataVO> paperDataVOList = new ArrayList<>();
			// 设置试卷包/试卷id、版本号
			packageDataVO.setId(paperDTO.getPaperId()).setVersion(Integer.valueOf(paperDTO.getPaperVersion()));
			// 获取试卷包/试卷中的试卷id和版本号（如果为单体试卷则只获取1对id和版本号）
			List<ExamPaperPackage> packagePaperDTOList = iExamPaperPackageService.getPackagePaperDTO(paperDTO.getPaperId(), paperDTO.getPaperVersion(), projectId);
			if (packagePaperDTOList.size() < 2) {
				// 单体试卷的情况下id为null，方便评卷处理数据
				packageDataVO.setId(null);
			}
			List<Integer> paperTypes = new ArrayList<>();
			paperTypes.add(1);  // 普通试卷
			paperTypes.add(5);  // 单题计时试卷
			// 去除性格测试卷
            packagePaperDTOList = packagePaperDTOList.stream().filter(packagePaper -> paperTypes.contains(packagePaper.getPaperType())).collect(Collectors.toList());
			// 根据试卷包/试卷id和版本号获取试卷数据
			for (ExamPaperPackage examPaperPackage : packagePaperDTOList) {
				// 统计试卷（或试卷包）下是否包含有主观题
				int count = examPaperMapper.countPackageSubjectiveItemNumber(projectId, examPaperPackage.getPaperId(), examPaperPackage.getPaperVersion());
				// 纯客观题试卷不给到评卷端
				if (count > 0) {
					PaperDataVO paperDataVO = this.getPaperData(examPaperPackage.getPaperId(), examPaperPackage.getPaperVersion());
					// 填空题单独处理，方便评卷处理数据
					paperDataVO.getTopicDataList().forEach(topicDataVO -> topicDataVO.getItemDataList().forEach(itemDataVO -> {
						if ("fill_in_blanks".equals(itemDataVO.getItemType())) {
							itemDataVO.getOptionsDataList().forEach(optionsDataVO -> optionsDataVO.setComposite(false));
						}
					}));
					paperDataVOList.add(paperDataVO);
				}
			}
			// 设置试卷数据
			packageDataVO.setPaperDataVOList(paperDataVOList);
			// 设置试卷包/试卷数据到试卷包/试卷List中
			packageDataVOList.add(packageDataVO);
		}
		List<PaperDataVO> papers = packageToPaper(packageDataVOList);
		return papers;
	}

	@DS("kw_read")
	public PaperDataVO getPaperData(String paperId, String paperVersion) {
		// 获取试卷数据基本信息
		PaperDataVO paperDataVO = sjPaperMapper.getPaperBaseData(paperId, paperVersion);
		if (paperDataVO == null) {
			return null;
		} else {
			// 授权码未导入
			if (paperDataVO.getPaperSources() == 1 && StringUtils.isBlank(paperDataVO.getPaperAuthCode())) {
				return null;
			}
		}
		// 获取大题数据列表
		List<TopicDataVO> topicList = sjPaperMapper.getTopicData(paperId, paperVersion);
		if (topicList == null) {
			return paperDataVO;
		}
		// 获取小题数据列表
		List<ItemDataVO> itemList = sjPaperMapper.getItemData(paperId, paperVersion);
		// 获取选项数据列表
		List<OptionsDataVO> optionList = sjPaperMapper.getOptionsData(paperId, paperVersion);
		// 组装数据
		if (!CollectionUtils.isEmpty(topicList)) {
			topicList = assemblePaperData(topicList, itemList, optionList);
		}
		paperDataVO.setTopicDataList(topicList);
		return paperDataVO;
	}

	/**
	 * 组装试卷数据
	 *
	 * @param topicList
	 *            试卷大题数据
	 * @param itemList
	 *            试卷小题数据
	 * @param optionList
	 *            试卷选项数据
	 * @return 试卷数据
	 */
	protected List<TopicDataVO> assemblePaperData(List<TopicDataVO> topicList, List<ItemDataVO> itemList, List<OptionsDataVO> optionList) {
		if (CollectionUtils.isEmpty(itemList)) {
			return topicList;
		}
		// 选项放入小题
		if (Objects.nonNull(optionList)) {
			itemList.stream().forEach(item -> {
				List<OptionsDataVO> itemOptionList = optionList.stream().filter(option -> option.getItemId().equals(item.getItemId())).sorted(Comparator.comparing(OptionsDataVO::getOptionSort))
						.collect(Collectors.toList());
				item.setOptionsDataList(itemOptionList);
			});
		}
		// 子小题放入父小题
		itemList.stream().forEach(pItem -> {
			List<ItemDataVO> childItemList = itemList.stream().filter(cItem -> pItem.getItemId().equals(cItem.getItemPid())).sorted(Comparator.comparing(ItemDataVO::getItemSort))
					.collect(Collectors.toList());
			pItem.setChildItemList(childItemList);
		});
		// 去掉子小题
		List<ItemDataVO> newItemList = itemList.stream().filter(item -> com.hyt.core.util.StringUtils.isEmpty(item.getItemPid())).collect(Collectors.toList());
		// 小题放入大题
		topicList.stream().forEach(topic -> {
			List<ItemDataVO> topicItemList = newItemList.stream().filter(item -> item.getTopicId().equals(topic.getTopicId())).sorted(Comparator.comparing(ItemDataVO::getItemSort))
					.collect(Collectors.toList());
			topic.setItemDataList(topicItemList);
		});
		return topicList;
	}

	/**
	 * 试卷包list转成试卷list
	 *
	 * @param packages
	 * @return
	 */
	private List<PaperDataVO> packageToPaper(List<PackageDataVO> packages) {
		List<PaperDataVO> allPapers = new ArrayList<>();
		List<PaperDataVO> paperVOs = null;
		for (PackageDataVO packageVO : packages) {
			paperVOs = packageVO.getPaperDataVOList();
			if (packageVO.getId() == null) {
				// 单体试卷
				if (paperVOs.size() > 0) {
					PaperDataVO paperVO = paperVOs.get(0);
					paperVO.setSort(1);
					allPapers.add(paperVO);
				}
			} else {
				int i = 0;
				for (PaperDataVO paperVO : paperVOs) {
					paperVO.setPackageId(packageVO.getId());
					paperVO.setPackageVersion(packageVO.getVersion());
					paperVO.setSort(i += 1);
					allPapers.add(paperVO);
				}
			}
		}
		return allPapers;
	}

	@DS("kw_read")
	@Override
	public ProjectVO getProjectInfo(String examId) {
		ProjectVO project = examCandidateMapper.getProjectInfo(examId);
		if (StringUtils.isNotBlank(project.getTaskId())) {
			NowTestNowDataVO nowTestNowDataVO = kwgovTaskService.getTaskExamType(project.getTaskId());
			if (null != nowTestNowDataVO) {
				project.setExamTypeName(nowTestNowDataVO.getTestClassifyName());
				project.setTaskBeginDate(DateTimeUtil.getFormatDateTime(nowTestNowDataVO.getBeginDate()));
				project.setTaskEndDate(DateTimeUtil.getFormatDateTime(nowTestNowDataVO.getEndDate()));
				project.setExamType(nowTestNowDataVO.getTestClassify());
			}
		}
		return project;
	}


	@DS("kw_read")
	@Override
	public List<PaperItemFile> getPaperItemFileData(String projectId, String paperId, String paperVersion) {
		List<PaperItemFile> paperItemFileData = sjItemFileMapper.getPaperItemFileData(paperId, paperVersion);
		if(CollectionUtil.isEmpty(paperItemFileData)){
			return paperItemFileData;
		}
		paperItemFileData.forEach(file ->{
			file.setProjectId(projectId);
		});
		return paperItemFileData;
	}
}
